package com.mindao.app.ued.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Hashtable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;



import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.mindao.app.common.base.controller.BaseCoreController;
import com.mindao.app.ea.api.InfEa;
import com.mindao.app.ea.model.User;
import com.mindao.utils.config.EaConstant;
import com.mindao.utils.hardinfo.HardInfo;
import com.mindao.utils.path.PathUtils;
@Controller
@RequestMapping("/loginUed")
public class LoginUedController extends BaseCoreController {
	private final Logger log = LoggerFactory.getLogger(LoginUedController.class);
	@RequestMapping(value="",method = RequestMethod.POST)
	public String execute (HttpServletResponse response,HttpServletRequest request,HttpSession session,Model rhs,String account, String password) throws Exception {
	    //数据初始化
		infEa.initData();
 
		if (StringUtils.isBlank(account)){
			rhs.addAttribute("tipInfo", "账号不存在!");
			return "login";
		}
		User user  = (User) infEa.getUserbyAccount(account);
		if (user==null) {
			rhs.addAttribute("tipInfo", "账号不存在!");
			return "login";
		}
		String result = infEa.checkLogin(account, password==null?"":password);
		
		//用户登录日志，to save in table
		String userinfo="姓名:"+ user.getName()+"  帐号:"+account;
		String clientinfo="\n    地址 "+request.getRemoteAddr()+"  机器：  "+request.getRemoteHost()
				+" \n    浏览器版本 "+request.getHeader("user-agent");
		log.info("\n"+userinfo+"  登录系统结果："+result+"!"+ clientinfo+"\n");
		
		if (result.equals("0000")) { // 验证成功
			putSessionValue(EaConstant.SESSION_USER_ACCOUNT, account);
			putSessionValue(EaConstant.SESSION_USER, user);
			putSessionValue(EaConstant.SESSION_USER_ID, user.getId());
			return "ued_frame";
		}else{
			rhs.addAttribute("tipInfo", "密码不正确!");
			return "login";
		}

	}
	/**
	 * 生成登录地址二维码
	 * @param module
	 * @param model
	 * @param page
	 * @param response
	 * @param request
	 * @param session
	 * @param rhs
	 * @throws Exception
	 */
	private void genQrpic(String url, int width, int height, String format,
			Hashtable hints,String filename) throws WriterException, IOException {
		BitMatrix bitMatrix = new MultiFormatWriter().encode(url,
				BarcodeFormat.QR_CODE, width, height, hints);
		
		log.debug("二维码文件保存地址"+filename);
		File outputFile = new File(filename);
		MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);
		
		
		
		
	}
	@RequestMapping
 	public void qrshow(HttpServletRequest request,HttpServletResponse response,HttpSession session,Model rhs)  throws Exception {

		String url ="http:/"+HardInfo.findNonLocalhostIp()+":"+request.getLocalPort()+request.getContextPath();
		
		// 如果不是第一次，还有用户名密码
		//Map sessionMap = ActionContext.getContext().getSession();
		
			
		rhs.addAttribute("url", url);
		Hashtable hints = new Hashtable();
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
		genQrpic(url, 200, 200,   "png",hints,PathUtils.getFileHome()+"qrhome.png");
 	    		
		FileInputStream fs =null;
 		try {
			File  file = new File(PathUtils.getFileHome()+"qrhome.png");
			
			fs =new FileInputStream(file);
			int len = (int)file.length();
			byte[] data = new byte[len];
			fs.read(data, 0, len);
			
			//if(data != null){
				response.setContentType("image/jpeg");
				response.setHeader("Cache-control", "no-cache ");
				response.getOutputStream().write(data);
				response.getOutputStream().flush();
			//}else{
			//	log.debug("无图片...");
			//}
 		} catch (Exception e) {
 			log.debug("图片不存在");
		}finally{
			if (fs!=null){
				fs.close();
			}
		}
 	 
	}
	
	
	@javax.annotation.Resource(name = "impEa")
	public void setInfEa(InfEa infEa) {
		this.infEa = infEa;
	}

	public InfEa getInfEa() {
		return infEa;
	}

}
